package servlet.cart;

import dao.GoodDao;
import entity.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@WebServlet("/cart/addCount")
public class AddCountServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String gid = request.getParameter("gid") ;
        System.out.println(gid);
        HttpSession session = request.getSession() ;
        Map<Goods , Integer> cart = (Map<Goods , Integer>)session.getAttribute("cart") ;
        //获取该商品的信息
        GoodDao gd = new GoodDao() ;
        Goods good = gd.loadByGid(gid) ;
        //取出购物车里的商品
        Set<Goods> goodsSet = cart.keySet() ;
        Integer count = 0;
        Iterator<Goods> iterator = goodsSet.iterator() ;
        while(iterator.hasNext()){
            //遍历，找出该商品，
            Goods g = iterator.next() ;
            if(g.equals(good)){
                //如果找到就增加数量
                 count = cart.get(g) +1;
                cart.replace(g , count) ;
                System.out.println(cart.get(g));
                break ;
            }
        }
        //更新session
        session.setAttribute("cart" , cart);
        response.setContentType("text/plain;charset=UTF-8" );
        response.getWriter().write("数量:" + count);
    }
}
